package com.ruoyi.file.controller;

import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.file.domain.ContractFile;
import com.ruoyi.file.service.IContractFileService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * contractFileController
 * 
 * @author zhangpu
 * @date 2024-05-10
 */
@RestController
@RequestMapping("/file")
public class ContractFileController extends BaseController
{
    @Autowired
    private IContractFileService contractFileService;

    /**
     * 查询contractFile列表
     */
    @RequiresPermissions("file:file:list")
    @GetMapping("/list")
    public TableDataInfo list(ContractFile contractFile)
    {
        startPage();
        List<ContractFile> list = contractFileService.selectContractFileList(contractFile);
        return getDataTable(list);
    }

    /**
     * 导出contractFile列表
     */
    @RequiresPermissions("file:file:export")
    @Log(title = "contractFile", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ContractFile contractFile)
    {
        List<ContractFile> list = contractFileService.selectContractFileList(contractFile);
        ExcelUtil<ContractFile> util = new ExcelUtil<ContractFile>(ContractFile.class);
        util.exportExcel(response, list, "contractFile数据");
    }

    /**
     * 获取contractFile详细信息
     */
    @RequiresPermissions("file:file:query")
//    @GetMapping(value = "/searchContractFile/{contractNo}")
//    @RequestMapping(value = "/searchContractFile/{contractNo}")
    @RequestMapping(value = "/searchContractFile")
    public List<ContractFile> getInfo(@RequestBody String contractNo)
    {
        System.out.println("根据合同编号查询附件列表");
        System.out.println(contractNo);
//        return success(contractFileService.selectContractFileById(id));
        ContractFile contractFile = new ContractFile();
        contractFile.setContractNo(contractNo);
        List<ContractFile> list = contractFileService.selectContractFileList(contractFile);
        return list;
    }

    /**
     * 新增contractFile
     */
    @RequiresPermissions("file:file:add")
    @Log(title = "contractFile", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody ContractFile contractFile)
    {
        System.out.println(contractFile);
        return toAjax(contractFileService.insertContractFile(contractFile));
    }

    /**
     * 修改contractFile
     */
    @RequiresPermissions("file:file:edit")
    @Log(title = "contractFile", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ContractFile contractFile)
    {
        return toAjax(contractFileService.updateContractFile(contractFile));
    }

    /**
     * 删除contractFile
     */
    @RequiresPermissions("file:file:remove")
    @Log(title = "contractFile", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(contractFileService.deleteContractFileByIds(ids));
    }

    @PostMapping("/downloadContractFile/{fileId}")
    public void downloadContractFile(HttpServletResponse response, @PathVariable String fileId){
        System.out.println("下载附件");
        System.out.println(fileId);
        ContractFile contractFile = contractFileService.selectContractFileById(fileId);
        BufferedInputStream bis = null;

        try {
            //下载文件
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream;charset=UTF-8");
            System.out.println(contractFile.getContractName()+contractFile.getFileName().substring(contractFile.getFileName().indexOf(".")));
            System.out.println(contractFile.getFileName());
//            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(contractFile.getContractName()+contractFile.getFileName().substring(contractFile.getFileName().indexOf(".")),"UTF-8"));
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("测试","UTF-8"));
//            response.setHeader("Content-Disposition", "attachment;filename=\"测试.docx\"");
            byte[] buff = new byte[1024];
            OutputStream os = null;
            os = response.getOutputStream();
            System.out.println(contractFile.getFilePath());
            bis = new BufferedInputStream(new FileInputStream(new File(contractFile.getFilePath())));
//            bis = new BufferedInputStream(new FileInputStream(new File("E:\\spring")));
            for(int i = bis.read(buff); i != -1; i = bis.read(buff)) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (Exception e) {

            e.printStackTrace();
            System.out.println("出现异常");
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }



    }


    @RequestMapping("/previewPDF/{pdfId}")
    public void previewPDF(HttpServletResponse response,@PathVariable("pdfId") String pdfId){
        System.out.println("预览PDF");
        System.out.println(pdfId);
//        ContractFile contractFile = contractFileService.selectContractFileById(fileId);
        ContractFile contractFile = new ContractFile();
        contractFile.setFileType("pdf");

        if(contractFile.getFileType().equals("pdf")){
            System.out.println("pdf");
//            String filePath = contractFile.getFilePath();
//            String filePath = "D:\\nccqFile\\1715237780256.pdf";
            String filePath = "D:\\nccqFile\\" + pdfId;

            System.out.println(filePath);
            File file = new File(filePath);
            if(file.exists()){
                System.out.println("文件存在");
                response.setContentType("application/pdf");
                response.setHeader("Content-Disposition", "inline; filename=" + contractFile.getFileName());
                try {
                    FileInputStream fileInputStream = new FileInputStream(file);
                    IOUtils.copy(fileInputStream, response.getOutputStream());
                    response.flushBuffer();
                    fileInputStream.close();
                    response.getOutputStream().flush();
                    response.getOutputStream().close();

               } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
       }

    }



}
